package com.open.source.monitor;

import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.math.BigDecimal;

/**
 * @author ZonLen since on 2021/12/12 下午1:17
 */
public final class ProcessMonitor {

  private static final Runtime RUNTIME = Runtime.getRuntime();
  private static final OperatingSystemMXBean SYSTEM_MX_BEAN = ManagementFactory
      .getPlatformMXBean(OperatingSystemMXBean.class);

  public static String memory() {
    //JVM最大内存
    final long maxMemory = RUNTIME.maxMemory() >> 20;
    //JVM进程当前总内存
    final long totalMemory = RUNTIME.totalMemory() >> 20;
    //JVM空闲内存
    final long freeMemory = RUNTIME.freeMemory() >> 20;
    //JVM当前占用内存
    final long jvmUsedMemory = totalMemory - freeMemory;
    final BigDecimal jvmUsed = BigDecimal.valueOf(100L).multiply(BigDecimal.valueOf(jvmUsedMemory))
        .divide(BigDecimal.valueOf(totalMemory), 2, BigDecimal.ROUND_FLOOR);
    //系统剩余内存
    final long freePhysicalMemorySize = SYSTEM_MX_BEAN.getFreePhysicalMemorySize() >> 20;
    //系统总内存
    final long totalPhysicalMemorySize = SYSTEM_MX_BEAN.getTotalPhysicalMemorySize() >> 20;
    //系统已使用
    final long systemUsedMemorySize = totalPhysicalMemorySize - freePhysicalMemorySize;
    //进程占用CUP
    final double processCpuLoad = SYSTEM_MX_BEAN.getProcessCpuLoad();
    //系统占用CPU
    final double systemCpuLoad = SYSTEM_MX_BEAN.getSystemCpuLoad();
    final String name = SYSTEM_MX_BEAN.getName();
    System.out.println(name + ";" + systemCpuLoad + ";" + processCpuLoad + ";");
    final BigDecimal systemUsed = BigDecimal.valueOf(100L)
        .multiply(BigDecimal.valueOf(systemUsedMemorySize))
        .divide(BigDecimal.valueOf(totalPhysicalMemorySize), 2, BigDecimal.ROUND_FLOOR);
    return "JVM最大内存:" + maxMemory + "MB;\nJVM进程当前总内存:" + totalMemory + "MB;\nJVM空闲内存:" + freeMemory
        + "MB;\nJVM当前占用内存:" + jvmUsedMemory + "MB;\nJVM内存使用率:" + jvmUsed + "%;\n系统剩余内存:"
        + freePhysicalMemorySize + "MB;\n系统总内存:" + totalPhysicalMemorySize + "MB;\n系统已使用:"
        + systemUsedMemorySize + "MB;\n系统内存利用率:" + systemUsed + "%;";
  }

  public static void main(String[] args) {
    System.out.println(memory());
  }

}
